#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define MQNAME "/mq_1123"

void child() {
  mqd_t mq = mq_open(MQNAME, O_RDONLY);
  if (mq < 0) {
    printf("[%d] open mq fail\n", getpid());
    return;
  }
  char msg[1024] = {0};
  unsigned int priority;
  while (mq_receive(mq, msg, 1024, &priority) != -1) {
    printf("[%d] recv data is %s\n", getpid(), msg);
  }
  mq_close(mq);
}

void parent() {
  struct mq_attr attr;
  // 最大消息数
  attr.mq_maxmsg = 10;
  // 每个消息最大长度
  attr.mq_msgsize = 1024;

  unsigned int priority = 0;
  mqd_t mq = mq_open(MQNAME, O_WRONLY | O_CREAT, 0666, &attr);
  if (mq < 0) {
    printf("[%d] open mq fail\n", getpid());
    return;
  }
  char msg[1024] = {0};
  for (int i = 0; i < 100; ++i) {
    snprintf(msg, 1024, "hello %d", i);
    if (mq_send(mq, msg, strlen(msg), priority) == -1) {
      printf("send message error");
      mq_close(mq);
      return;
    }
  }
  mq_close(mq);
}

int main() {
  printf("hello\n");
  int pid = fork();
  if (pid == 0) {
    // 子进程
    printf("child\n");
    child();
  } else {
    // 父进程
    printf("parent\n");
    parent();
  }
}